﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using YAGMRC.Core.Models.GetGamesAndPlayers;
using YAGMRC.Core.OS;

namespace YAGMRC.Core.Commands
{
    public class GetLatestSaveFileBytesCommand : ICommand<GetLatestSaveFileBytesCommandParam>
    {
        #region Constructor

        private GetLatestSaveFileBytesCommand()
        {
        }

        internal GetLatestSaveFileBytesCommand(Resolver resolver)
        {
            m_Resolver = resolver;
        }

        #endregion Constructor

        private Resolver m_Resolver;

        public void Execute(GetLatestSaveFileBytesCommandParam parameter)
        {
            if (!this.CanExecute())
            {
                return;
            }

            DownloadExecute executeWeb = m_Resolver.Get<DownloadExecute>();

            int gameid = parameter.GameID;
            {
                GetGamesAndPlayersCommandResult games = m_Resolver.Get<GetGamesAndPlayersCommandResult>();
                Game foundGame = (from id in games.Result.Games where id.GameId == gameid select id).FirstOrDefault();
                if (null == foundGame)
                {
                    return;
                }
                AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();
                executeWeb.Execute("GetLatestSaveFileBytes?authKey=" + auth.AuthID + "&gameId=" + foundGame.GameId.ToString());
                byte[] webResult = executeWeb.Result;

                string path = m_Resolver.Get<IOSSetting>().CIVSaveGamePath.FullName;

                Directory.CreateDirectory(path);

                FileInfo fi = Helper.File(gameid, m_Resolver.Get<IOSSetting>());
                if (fi.Exists)
                {
                    fi.Delete();
                }

                File.WriteAllBytes(fi.FullName, webResult);
            }
        }

        public bool CanExecute()
        {
            AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();
            GetGamesAndPlayersCommandResult games = m_Resolver.Get<GetGamesAndPlayersCommandResult>();
            return (games.HasResult) && ((null != auth) && (auth.Authenticated));
        }
    }
}